package cn.fastoo.task;


import cn.fastoo.common.dao.UserBalanceRemindDao;
import cn.fastoo.common.dao.UserBalanceRemindRecordDao;
import cn.fastoo.common.dao.UserBaseDao;
import cn.fastoo.common.entity.UserBalanceRemind;
import cn.fastoo.common.entity.UserBalanceRemindRecord;
import cn.fastoo.common.entity.UserBase;
import cn.fastoo.common.sampleframe.search.Search;

import cn.fastoo.common.utils.DateUtils;
import cn.fastoo.common.utils.SmsSender;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 余额提醒
 * 
 * @author daniel.chan
 */
@Component
public class RemindTimer {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserBaseDao userBaseDao;
    @Autowired
    private UserBalanceRemindDao userBalanceRemindDao;
    @Autowired
    private UserBalanceRemindRecordDao userBalanceRemindRecordDao;


    @PostConstruct
    public void init() {
        /**
         * 余额提醒
         */
        ScheduledExecutorService fixedTimer = Executors.newScheduledThreadPool(1);
        fixedTimer.scheduleAtFixedRate(new Runnable() {
            public void run() {
                logger.info("remind balance start ...");
                doRemind();
                logger.info("remind balance end !!!");
            }
        }, 1, 30, TimeUnit.MINUTES); //每30分钟调用一次
    }

    private void doRemind() {
        List<UserBalanceRemind> list = userBalanceRemindDao.find(new Search());
        if (list.size()>0){
            for (UserBalanceRemind remind : list){
                try {
                    //获取用户定义的发送提醒时间
                    String remindRangeTime = remind.getRemindRangeTime();
                    String startTime = remindRangeTime.split("-")[0];
                    String endTime = remindRangeTime.split("-")[1];
                    Integer start = Integer.valueOf(startTime.replaceAll(":",""));
                    Integer end = Integer.valueOf(endTime.replaceAll(":",""));
                    Date now = new Date();
                    Integer hm = Integer.valueOf(DateUtils.getHourMinute(now));

                    //若在设置的时间内容提醒
                    if (start<=hm&&hm<=end) {
                        Long userBaseId = remind.getUserBaseId();
                        UserBase userBase = userBaseDao.findById(userBaseId);
                        if (userBase==null) {
                            logger.info("userBaseId="+userBaseId+"不存在");
                            break;
                        }
                        //金额达到提醒额度且上一次提醒时间小于最近一次的充值时间
                        logger.info("开始余额提醒是否满足条件userBaseId="+userBaseId+"："+((remind.getLastRemindTime() == null&&remind.getLastChargeTime()!=null)||(remind.getLastRemindTime() != null && remind.getLastChargeTime() != null&&remind.getLastRemindTime().getTime() < remind.getLastChargeTime().getTime())));
                        if (remind.getRemindBalance() >= userBase.getBalance()){
                            if ((remind.getLastRemindTime() == null&&remind.getLastChargeTime()!=null)
                                    ||(remind.getLastRemindTime() != null && remind.getLastChargeTime() != null&&remind.getLastRemindTime().getTime() < remind.getLastChargeTime().getTime())) {
                                //发送余额提醒短信
                                String receiveMobile = userBase.getLoginName();
                                //判断接收号码是否为空
                                if (StringUtils.isNotBlank(receiveMobile)) {
                                    logger.info("开始余额提醒receiveMobile=" + receiveMobile);
                                    String msgcontent = "尊敬的非常快API客户，您的【" + userBase.getLoginName() + "】账户金额不足" + remind.getRemindBalance() + "元，请及时充值以免影响您的正常使用。";
                                    logger.info(SmsSender.sendCaptchSms("86" + receiveMobile, msgcontent));

                                    //写入数据库
                                    UserBalanceRemindRecord remindRecord = new UserBalanceRemindRecord();
                                    remindRecord.setUserBaseId(userBaseId);
                                    remindRecord.setReceiveMobile(receiveMobile);
                                    remindRecord.setMsgContent(msgcontent);
                                    remindRecord.setRemark("loginName=" + userBase.getLoginName() + "当前金额：" + userBase.getBalance() + ",金额不足提醒");
                                    remindRecord.setSaveTime(new Date());
                                    userBalanceRemindRecordDao.insert(remindRecord);

                                    //更新系统提醒时间
                                    remind.setLastRemindTime(new Date());
                                    userBalanceRemindDao.update(remind);
                                }
                            }
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    logger.info("发送余额提醒失败:",e);
                }
            }
        }
    }

}
